<template>
  <view class="w-full min-h-screen bg-gray-50">
    <!-- 使用 scroll-view 实现滚动加载 -->
    <scroll-view scroll-y class="h-screen p-4" :scroll-top="scrollTop" @scrolltolower="loadMore" @scroll="handleScroll"
                 :scroll-with-animation="true">
      <!-- 列表内容 -->
      <view class="space-y-4">
        <view
            v-for="item in pageData.content"
            :key="item.id"
            class="bg-white rounded-lg shadow-sm border border-gray-100 overflow-hidden"
            @click="toggleExpand(item.id)"
        >
          <view class="p-4 flex justify-between items-start">
            <view>
              <text class="font-medium text-lg block">{{ item.hostName }}</text>
              <text class="text-gray-500 text-sm">{{ item.visitStartTime.substring(0, 16) }}</text>
            </view>
            <view class="flex items-center">
              <view class="px-2 py-1 rounded text-xs" :class="statusClass[item.status]">
                <TextDisplay :value="item.status" :options="statusTypes"/>
              </view>
              <uni-icons
                  :type="expandedItems.includes(item.id) ? 'arrowup' : 'arrowdown'"
                  size="16"
                  class="ml-2 text-gray-400"/>
            </view>
          </view>

          <!-- 折叠详情 -->
          <view
              v-if="expandedItems.includes(item.id)"
              class="px-4 pb-4 pt-2 bg-gray-50 border-t border-gray-100">
            <view class="grid grid-cols-2 gap-y-3 text-sm">
              <template v-for="(field, index) in detailFields" :key="index">
                <view class="text-gray-500">{{ field.label }}:</view>
                <template v-if="field.enumeration">
                  <TextDisplay :value="item[field.key]" :options="field.enumeration"/>
                </template>
                <template v-else-if="field.children">
                  <view class="col-span-1">
                    <view v-for="(child, i) in item[field.key]" :key="i" class="mb-1 last:mb-0">
                      {{ child.companionName }} ({{ child.companionPhone }})
                    </view>
                  </view>
                </template>
                <template v-else>
                  <view>{{ item[field.key] || field.default }}</view>
                </template>
              </template>
            </view>
          </view>
        </view>

        <!-- 加载状态指示器 -->
        <view v-if="loading" class="py-4 flex justify-center">
          <uni-load-more status="loading"/>
        </view>

        <!-- 没有更多数据提示 -->
        <view v-if="isLastPage && pageData.content.length > 0" class="py-4 text-center text-gray-500 text-sm">
          已经到底了
        </view>

        <!-- 空状态 -->
        <view v-if="!loading && pageData.content.length === 0" class="py-10 flex flex-col items-center justify-center">
          <uni-icons type="contact" size="48" color="#999"/>
          <text class="text-gray-500 mt-2">暂无访客记录</text>
          <button class="mt-4 text-blue-500 text-sm" @click="refresh">刷新试试</button>
        </view>
      </view>
    </scroll-view>

    <!-- 返回顶部按钮（滚动超过300px显示） -->
    <view
        v-if="showBackTop"
        class="fixed right-4 bottom-20 bg-white p-2 rounded-full shadow-md border border-gray-200 z-10"
        @click="scrollToTop">
      <uni-icons type="arrowup" size="20" color="#666"/>
    </view>
  </view>
</template>

<script setup>
import {computed, ref} from 'vue'
import {onShow} from '@dcloudio/uni-app'
import {getApprovalStatusEnum, getVisitorHistoryPageApi, getVisitorTypes} from "@/api/visitor";
import TextDisplay from "@/common/TextDisplay.vue";
import {useAuthStore} from "@/stores/authStore";

const authStore = useAuthStore();

// 数据状态
const loading = ref(false);
const isLastPage = ref(false);
const pageData = ref({page: 1, size: 10, total: 0, content: []});
const visitorTypes = ref([])
const statusTypes = ref([]);
// 滚动状态
const scrollTop = ref(0);
const showBackTop = ref(false);
// UI配置
const statusClass = {
  PENDING: 'bg-yellow-100 text-yellow-800',
  APPROVED: 'bg-green-100 text-green-800',
  REJECTED: 'bg-red-100 text-red-800',
};

const detailFields = computed(() => {
  return [
    {label: '来访人', key: 'visitorName'},
    {label: '联系电话', key: 'visitorPhone'},
    {label: '来访类型', key: 'visitorType', enumeration: visitorTypes.value},
    {label: '来访公司', key: 'company'},
    {label: '车牌号', key: 'carNumber', default: '无'},
    {label: '访问事由', key: 'purpose'},
    {label: '陪同人员', key: 'companions', children: true, show: item => item.companions?.length > 0},
    {label: '创建时间', key: 'createTime'},
    {label: '审核人', key: 'approver', show: item => item.status && item.status !== 'PENDING'},
    {label: '审核备注', key: 'approvalComment', show: item => item.approvalComment},
  ]
});

// 展开/折叠逻辑
const expandedItems = ref([]);
const toggleExpand = (id) => {
  const index = expandedItems.value.indexOf(id);
  index > -1 ? expandedItems.value.splice(index, 1) : expandedItems.value.push(id);
};

// 滚动处理
const handleScroll = (e) => {
  showBackTop.value = e.detail.scrollTop > 300;
};

const scrollToTop = () => {
  scrollTop.value = scrollTop.value ? 0 : 1;
};

// 数据加载
const fetchVisitorList = async (isLoadMore = false) => {
  if (loading.value) {
    return;
  }

  loading.value = true;

  try {
    let param = {
      page: isLoadMore ? pageData.value.page + 1 : 1,
      size: pageData.value.size,
      wxOpenid: authStore.wxOpenid
    }
    const res = await getVisitorHistoryPageApi(param);
    if (res.code !== 'SUCCESS') {
      return
    }
    pageData.value.content = isLoadMore ? pageData.value.content.concat(res.data.content) : res.data.content
    pageData.value.total = res.data.totalElements
    pageData.value.page = isLoadMore ? pageData.value.page + 1 : 1
    isLastPage.value = pageData.value.page * pageData.value.size >= pageData.value.total;
  } catch (error) {
    console.error('获取数据失败:', error);
    uni.showToast({title: error.message, icon: 'none'})
  } finally {
    loading.value = false;
  }
};

const fetchApproveStatus = async () => {
  const res = await getApprovalStatusEnum()
  if (res.code !== 'SUCCESS') {
    return
  }
  statusTypes.value = res.data.map(item => ({
    text: item.label,
    value: item.value
  }))
}
const fetchVisitorTypes = async () => {
  const res = await getVisitorTypes()
  if (res.code !== 'SUCCESS') {
    return
  }
  visitorTypes.value = res.data.map(item => ({
    text: item.label,
    value: item.value
  }))
}
// 加载更多
const loadMore = () => fetchVisitorList(true);

// 刷新数据
const refresh = () => {
  fetchVisitorList();
};

// 初始化
onShow(() => {
  fetchApproveStatus()
  fetchVisitorTypes()
  refresh()
})
</script>

<style scoped>
</style>